package com.ruoyi.common.core.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description:SmsService
 * @author: caoes
 * create:2023/6/29 10:15
 **/
@Component
public class SmsSendService {

    private static final Logger logger = LoggerFactory.getLogger(SmsSendService.class);
    @Autowired
    private SmsConfig smsConfig;

    /**
     * sendSmsCode
     * @param phone
     */
    public void sendSmsCode(String phone, String content) {

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAccessKey(), smsConfig.getAccessKeySecret());
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        //接收短信的手机号码
        request.setPhoneNumbers(phone);
        //短信签名名称
        request.setSignName(smsConfig.getSignName());
        //短信模板CODE
        request.setTemplateCode(smsConfig.getTemplateCode());
        //短信模板变量对应的实际值
        request.setTemplateParam("{\"code\":\""+content+"\"}");
        try {
            SendSmsResponse response = acsClient.getAcsResponse(request);
            if (!"OK".equals(response.getCode())) {
                throw new RuntimeException(String.format("发送短信失败:%s", response.getMessage()));
            }
        } catch (ClientException e) {
            logger.error("短信发送异常:{}", e);
            throw new RuntimeException(e.getErrMsg());
        }
    }
}
